﻿using AutoMapper;
using DTcms.Core.Common.Emum;
using DTcms.Core.DBFactory.Database;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using Microsoft.EntityFrameworkCore;

namespace DTcms.Core.Services
{
    /// <summary>
    /// 文章附件接口实现
    /// </summary>
    public class ArticleAttachService : BaseService, IArticleAttachService
    {
        private readonly IMapper _mapper;
        private readonly IUserService _userService;
        private readonly IArticleService _articleService;

        public ArticleAttachService(IDbContextFactory contentFactory, IUserService userService, IArticleService articleService, IMapper mapper) : base(contentFactory)
        {
            _userService = userService;
            _mapper = mapper;
            _articleService = articleService;
        }

        /// <summary>
        /// 更新下载数量
        /// </summary>
        /// <param name="id">附件主键</param>
        /// <param name="appUser">当前登录用户的信息</param>
        /// <param name="writeAndRead"></param>
        /// <returns></returns>
        public async Task<bool> UpdateDownCount(long id, ApplicationUser appUser, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var model = await _context.Set<ArticleAttach>().FirstOrDefaultAsync(t => t.Id == id);
            if (model == null) return false;
            //修改下载数量
            model.DownCount = model.DownCount + 1;
            //添加下载日志
            if (appUser != null)
            {
                MemberAttachLog attachLog = new()
                {
                    AddTime = DateTime.Now,
                    AttachId = id,
                    FileName = model.FileName,
                    UserId = appUser.Id
                };
                await _context.Set<MemberAttachLog>().AddAsync(attachLog);
            }
            return await _context.SaveChangesAsync() > 0;
        }
    }
}
